package com.jy.appmarket.screenlock.view;

import java.util.List;

import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.screenlock.prefs.LockPrefs;
import com.jy.appmarket.screenlock.utils.PatternLockerUtils;
import com.jy.appmarket.screenlock.view.PatternLockerView.Cell;

import android.content.Context;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 类说明：
 * 
 * @author kalui.huang
 * @date 2015-3-10
 * @version 1.0
 */
public class PatternPasswordView extends LinearLayout {
	// private static final String TYPE = "pattern_type";// 确认密码
	public static final int CONFIRM_PSW = 1;// 确认密码
	public static final int UNLOCK_PSW = 2;// 主界面解锁
	private View mContentView;
	private PatternLockerView mLockPatternView;

	private int mFailedPatternAttemptsSinceLastTimeout = 0;
	private Handler mHandler = new Handler();
	private TextView mHeadTextView;
	private Animation mShakeAnim;

	private Context mContext;
	private int mType;

	private OnPatternViewListener listener;

	public enum PatternViewResult {
		UNLOCK, BACK, EMS_CALL
	}

	public void setOnPatternViewListener(OnPatternViewListener listener) {
		this.listener = listener;
	}

	public PatternPasswordView(Context context) {
		super(context);
		mContext = context;
		initView();
	}

	private void initView() {
		mContentView = LayoutInflater.from(mContext).inflate(R.layout.fragment_pattern_password, this);
		mContentView.findViewById(R.id.fragment_pattern_bottom_layout).setVisibility(View.VISIBLE);
		mLockPatternView = mContentView.findViewById(R.id.fragment_locker_view);
		mHeadTextView = mContentView.findViewById(R.id.fragment_pattern_hint);
		mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
		if (LockPrefs.getTouchSoundFeedback(mContext)) {
			mLockPatternView.setTactileFeedbackEnabled(true);
		} else {
			mLockPatternView.setTactileFeedbackEnabled(false);
		}

		LinearLayout patternLayout = mContentView.findViewById(R.id.number_layout);
		patternLayout.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				switch (arg1.getAction()) {
				case MotionEvent.ACTION_DOWN:
					// 添加此句表示在这个view内滑动时无需理会父类的滑动动作
					getParent().requestDisallowInterceptTouchEvent(true);
					return true;
				case MotionEvent.ACTION_UP:
					arg0.performClick();
					return true;
				default:
					return false;
				}
			}
		});

		mShakeAnim = AnimationUtils.loadAnimation(mContext, R.anim.shake_x);
		// 紧急电话
		if (CONFIRM_PSW == mType) {
			mContentView.findViewById(R.id.emergency_call_tv).setVisibility(View.INVISIBLE);
			mContentView.findViewById(R.id.delete_tv).setVisibility(View.INVISIBLE);
		}
		// 暂时屏蔽
		mContentView.findViewById(R.id.emergency_call_tv).setVisibility(View.INVISIBLE);

		mContentView.findViewById(R.id.emergency_call_tv).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				listener.onPattern(PatternViewResult.EMS_CALL);
				// ComponentName comp = new ComponentName("com.android.phone",
				// "com.android.phone.EmergencyDialer");
				// Intent intent = new Intent();
				// intent.setComponent(comp);
				// mActivity.startActivity(intent);
			}
		});
		mContentView.findViewById(R.id.delete_tv).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				listener.onPattern(PatternViewResult.BACK);
			}
		});
	}

	private Runnable mClearPatternRunnable = new Runnable() {
		public void run() {
			mLockPatternView.clearPattern();
			mHeadTextView.setText("请绘制图案密码");
		}
	};
	protected PatternLockerView.OnPatternListener mChooseNewLockPatternListener = new PatternLockerView.OnPatternListener() {

		public void onPatternStart() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
			patternInProgress();
		}

		public void onPatternCleared() {
			mLockPatternView.removeCallbacks(mClearPatternRunnable);
		}

		public void onPatternDetected(List<PatternLockerView.Cell> pattern) {
			if (pattern == null)
				return;
			if (AppMarketApplication.getLockPatternUtils().checkPattern(pattern)) {
				mLockPatternView.setDisplayMode(PatternLockerView.DisplayMode.Correct);
				listener.onPattern(PatternViewResult.UNLOCK);
			} else {
				mLockPatternView.setDisplayMode(PatternLockerView.DisplayMode.Wrong);
				if (pattern.size() >= PatternLockerUtils.MIN_PATTERN_REGISTER_FAIL) {
					mFailedPatternAttemptsSinceLastTimeout++;
					int retry = PatternLockerUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT
							- mFailedPatternAttemptsSinceLastTimeout;
					if (retry >= 0) {
						if (retry == 0)
							mHeadTextView.setText("您已5次输错密码，请3分钟后再试");
						else {
							mHeadTextView.setText("密码错误，还可以再输入" + retry + "次");
						}
						mHeadTextView.startAnimation(mShakeAnim);
					}

				} else {
					mHeadTextView.setText("输入长度不够，请重试");
					mHeadTextView.setTextColor(Color.WHITE);
				}

				if (mFailedPatternAttemptsSinceLastTimeout >= PatternLockerUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) {
					mHandler.postDelayed(attemptLockout, 2000);
				} else {
					mLockPatternView.postDelayed(mClearPatternRunnable, 2000);
				}
			}
		}

		@Override
		public void onPatternCellAdded(List<Cell> pattern) {

		}

		private void patternInProgress() {
		}

	};

	Runnable attemptLockout = new Runnable() {

		@Override
		public void run() {
			mLockPatternView.clearPattern();
			mLockPatternView.setEnabled(false);
			new CountDownTimer(PatternLockerUtils.FAILED_ATTEMPT_TIMEOUT_MS + 1, 1000) {
				@Override
				public void onTick(long millisUntilFinished) {
					String remainingText = "";
					int secondsRemaining = (int) (millisUntilFinished / 1000) - 1;
					if (secondsRemaining >= 60) {
						remainingText = secondsRemaining / 60 + "分" + secondsRemaining % 60 + "秒后重试";
					} else {
						remainingText = secondsRemaining + " 秒后重试";
					}
					if (secondsRemaining > 0) {
						mHeadTextView.setText(remainingText);
					} else {
						mHeadTextView.setText("请绘制图案密码");
						mHeadTextView.setTextColor(Color.WHITE);
					}
				}

				@Override
				public void onFinish() {
					mLockPatternView.setEnabled(true);
					mFailedPatternAttemptsSinceLastTimeout = 0;
				}
			}.start();
		}
	};

	public interface OnPatternViewListener {
		void onPattern(PatternViewResult result);
	}
}
